﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Newtonsoft.Json;
using System.Text;
using System.Data;
using ReportTracking.ReportTrackingDTT;

namespace ReportTracking.Services
{
    /// <summary>
    /// Summary description for PL2
    /// </summary>
    public class PL2G : IHttpHandler, IReadOnlySessionState
    {
        ReportTracking.ReportTrackingDTT.TrackingReportClient rptrk = new ReportTracking.ReportTrackingDTT.TrackingReportClient();
        static string sPath = "";
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            sPath = context.Request.PhysicalApplicationPath + "XMLData/speed.xml";
            /*string sDVKD = context.Request.QueryString["dvkd"];
            DateTime sfd = Convert.ToDateTime(context.Request.QueryString["fd"]);
            DateTime std = Convert.ToDateTime(context.Request.QueryString["td"]);
            int nReportType = Convert.ToInt32(context.Request.QueryString["reporttype"]);
             */
            string sparam = context.Request.QueryString["param"];
            Dictionary<string, string> value = JsonConvert.DeserializeObject<Dictionary<string, string>>(sparam);
            
            string sDVKD = value["dvkd"];
            DateTime sfd = Convert.ToDateTime(value["fd"]);
            DateTime std = Convert.ToDateTime(value["td"]);
            int nReportType = Convert.ToInt32(value["reporttype"]);

            int page = Convert.ToInt32(context.Request.QueryString["page"]);
            int nRows = Convert.ToInt32(context.Request.QueryString["rows"]);
            string sReload = HttpContext.Current.Request.Cookies["bRequest"].Value;
            string[] sArrDVDK = sDVKD.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            int nTotal = 0;
            int nPage = 0;
            StringBuilder sData = new StringBuilder();
            string sTable = "";

            if (sReload == "0")
            {
                string[] arrLPT = new string[] { };
                float[] arrSpeed = new float[] { };
                GetSpeedDefault(ref arrLPT, ref arrSpeed);
                context.Session["Data"] = null;
                context.Session["InfoReprot"] = null;
                if (sArrDVDK.Length >0)
                {
                    if (sArrDVDK[0] =="All" )
                    {
                        sArrDVDK = null;
                    }   
                }
                sTable = Newtonsoft.Json.JsonConvert.SerializeObject(GetData(sfd, std, ref nTotal, arrLPT,  arrSpeed, ref nPage, sArrDVDK, (page - 1) * nRows, nRows));
                InfoReport inforeport = new InfoReport(String.Format("{0:d/M/yyyy}", sfd), String.Format("{0:d/M/yyyy}", std), sArrDVDK, nTotal, nReportType, "");
                context.Session["InfoReprot"] = inforeport;
            }
            else
            {
                DataTable tb = (DataTable)context.Session["Data"];
                sTable = Newtonsoft.Json.JsonConvert.SerializeObject(DivPage(ref nTotal, ref nPage,(page - 1) * nRows, nRows));

            }

            sData.Append("{");
            sData.Append("page:");
            sData.Append(page);
            sData.Append(",");
            sData.Append("total:");
            sData.Append(nPage);
            sData.Append(",");
            sData.Append("records:");
            sData.Append(nTotal);
            sData.Append(",");
            sData.Append("rows:");
            sData.Append(sTable);
            sData.Append("}");
            context.Response.Write(Newtonsoft.Json.JsonConvert.DeserializeObject(sData.ToString()));
        }
        private DataTable GetData(DateTime sFromDay, DateTime sToDay, ref  int total, string[] arrLPT, float[] arrSpeed, ref int nPage, string[] sArrDVDK, int nFromRecords, int nNumberRecords)
        {
            try
            {
                DataTable tb = rptrk.GetReportSpeed(sArrDVDK, arrLPT, arrSpeed, sFromDay, sToDay).Tables[0];
                HttpContext.Current.Session["Data"] = tb;
                total = tb.Rows.Count;
                nPage = Utilities.PageNumber(total, nNumberRecords);
                if (tb.Rows.Count > 0)
                {
                    IEnumerable<DataRow> results = (from myRow in tb.AsEnumerable().Skip(nFromRecords).Take(nNumberRecords)
                                                    select myRow);
                    return ReturnData(results);
                }
            }
            catch (System.Exception ex)
            {
                return null;
            }
            return null;
        }

        private DataTable DivPage(ref int nTotal, ref int nPage, int fromreocrds = 0, int torecords = 100)
        {
            DataTable tb = (DataTable)HttpContext.Current.Session["Data"];
            nTotal = tb.Rows.Count;
            nPage = Utilities.PageNumber(nTotal, torecords);
            if (tb.Rows.Count > 0)
            {
                IEnumerable<DataRow> results = (from myRow in tb.AsEnumerable().Skip(fromreocrds).Take(torecords)
                                                select myRow);

                return ReturnData(results);
            }
            return null;


        }

        private DataTable ReturnData(IEnumerable<DataRow> dtr)
        {
            DataTable tb = CreateDatatable();
            foreach (var dr in dtr)
            {
                tb.Rows.Add(dr["PlateNumber"], dr["BusinessUnitType"], Utilities.EditString(dr["BusinessUnit"].ToString(), @"\s", "</br>", 3), "<a href='http://222.255.236.179/FMSTrackingweb/'>" + Utilities.EditString(dr["DriverName"].ToString(), @"\s", "</br>", 3) + "</a>", dr["LicenseNumber"],
                Utilities.EditString(String.Format("{0:d/M/yyyy}", dr["Date"]), @"\s", "</br>", 2), String.Format("{0:0.00}", dr["TotalDistance"]), dr["Less10Km"], dr["Between10Km20Km"], dr["Great20Km"], Utilities.EditString(dr["Note"].ToString(), @"\s", "</br>", 10));
            }
            return tb;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        private static DataTable CreateDatatable()
        {
            DataTable tb = new DataTable();
            tb.Columns.Add("BKS", typeof(string));
            tb.Columns.Add("LHHD", typeof(string));
            //tb.Columns.Add("DVQL", typeof(string));
            tb.Columns.Add("DVKD", typeof(string));
            tb.Columns.Add("HTTX", typeof(string));
            tb.Columns.Add("GPLX", typeof(string));
            tb.Columns.Add("NGAYHD", typeof(string));
            tb.Columns.Add("TKM", typeof(double));
            /*tb.Columns.Add("TL1", typeof(string));
            tb.Columns.Add("SL1", typeof(int));
            tb.Columns.Add("TL2", typeof(string));*/
            tb.Columns.Add("SL3", typeof(int));
            tb.Columns.Add("SL4", typeof(int));
            tb.Columns.Add("SL5", typeof(int));
            tb.Columns.Add("Note", typeof(string));
            tb.Dispose();
            return tb;

        }
        private void GetSpeedDefault(ref string[] arrLPT, ref float[] arrSpeed)
        {
                ReportTracking.DefinedSpeed dfsp = new ReportTracking.DefinedSpeed(sPath);
                if (dfsp.LoadXML().Tables[0].Rows.Count > 0)
                {
                    DataTable tb = dfsp.LoadXML().Tables[0];
                    for (int i = 0; i < tb.Rows.Count; i++)
                    {
                        Array.Resize<string>(ref arrLPT, arrLPT.Length + 1);
                        arrLPT[arrLPT.Length - 1] = tb.Rows[i]["LPT"].ToString();
                        Array.Resize<float>(ref arrSpeed, arrSpeed.Length + 1);
                        arrSpeed[arrSpeed.Length - 1] = (float)Convert.ToDouble(tb.Rows[i]["VANTOC"]);
                    }
                }
          
        }
    }
}